# -*- coding: utf-8 -*-
"""
@Time ： 2020/11/2 21:59
@Auth ： Mr. William 1052949192
@Company ：特斯汀学院 @testingedu.com.cn
@Function ：请输入模块功能描述
"""
import time

import cv2
import requests
from selenium.webdriver import ActionChains


class Slide:
    """
    滑动验证码识别的类
    """
    def __init__(self,driver):
        # 浏览器对象
        self.driver = driver

    def slide(self,target='None',template='None'):
        """
        滑动验证码识别和滑动实现
        :return: 是否成功
        """
        while True:
            # 下载背景原图和模块原图
            # 背景图
            ele_target = self.driver.find_element_by_xpath(target)
            ele_template = self.driver.find_element_by_xpath(template)
            target_src = ele_target.get_attribute('src')
            template_src = ele_template.get_attribute('src')

            # 下载
            target_img = requests.get(target_src).content
            f = open('../verify/imgs/target.png', mode='wb')
            f.write(target_img)
            f.close()

            template_img = requests.get(template_src).content
            with open('../verify/imgs/template.png', mode='wb') as f:
                f.write(template_img)
            f.close()

            w1 = ele_target.size['width']

            # 打开背景图
            target_rgb = cv2.imread('../verify/imgs/target.png')
            w2 = target_rgb.shape[1]
            # 灰度处理
            target_gray = cv2.cvtColor(target_rgb, cv2.COLOR_BGR2GRAY)
            # 打开模板图
            template_rgb = cv2.imread('../verify/imgs/template.png', 0)
            # 获取模板在背景图的位置
            res = cv2.matchTemplate(target_gray, template_rgb, cv2.TM_CCOEFF_NORMED)
            # 获取最好和最差的匹配
            value = cv2.minMaxLoc(res)
            x = value[2][0] + 23
            # 计算缩放之后的x距离
            x = int(x * w1 / w2) - 32
            print('左边界：%d' % x)

            # 滑动
            action = ActionChains(self.driver)
            action.click_and_hold(ele_template).perform()
            action.move_by_offset(x, 0).perform()
            action.release().perform()
            time.sleep(2)
            try:
                self.driver.implicitly_wait(3)
                ele = self.driver.find_element_by_xpath('//*[@id="e_reload"]')
                ele.click()
            except Exception as e:
                self.driver.implicitly_wait(10)
                break

        self.driver.implicitly_wait(10)
